﻿define [
    'jquery'
    'use!underscore'
    'use!backbone'
    'namespace'
    'photo'
    'album'
    'photoView'
    'text!templates/show_photo.html'
    'text!templates/edit_photo.html'
    'jquery_ui'
], ($, _, Backbone, global, Photo, Album, PhotoView, ShowPhotoTemplate, EditPhotoTemplate) ->
  AddView = Backbone.View.extend(
    tagName: 'figure'
    attributes:
      class: 'photo'
      id: 'add'

    templateFunc:
      show: _.template(ShowPhotoTemplate)
      edit: _.template(EditPhotoTemplate)

    render: (template) ->
      @$el.html @templateFunc[template](new Photo().toJSON())
      _.each $('.datepicker'), (input) ->
        $(input).datepicker
          dateFormat: 'yy-mm-dd'
          currentText: input.value
      this

    events:
      'click #cancel': 'cancelAdd'
      'click #save': 'addPhoto'

    cancelAdd: (e) ->
      e.preventDefault()
      @remove()
      global.app.router.navigate '/'

    addPhoto: ->
      formData = {}
      @$el.find('input').each ->
        $input = $(this)
        formData[$input.attr('id')] = $input.val()

      newModel = new Photo(formData)
      newModel.set 'type', $('#album :selected').val(),
        silent: true

      Album.url = '/Photo/'
      Album.create newModel,
        wait: true

      @remove()
      photo = new PhotoView(model: newModel)
      $('.photo:first').before photo.render('show').el
      global.app.router.navigate '/'
  )
